package com.kimho.user.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kimho.core.PageInfo;
import com.kimho.menu.domain.Menu;
import com.kimho.menu.service.MenuService;
import com.kimho.user.domain.User;
import com.kimho.user.service.UserService;
import com.kimho.util.Util;
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;
	/**
	 * 登录验证
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public @ResponseBody Map<String,String> loginCheck(HttpServletRequest request,   
            HttpServletResponse response){
		//spring会利用jackson自动将返回值封装成JSON对象
		Map<String,String> responseMap = new HashMap<String,String>();
		String captcha = request.getParameter("captcha");
		String staff_code = request.getParameter("staff_code");
		String password = request.getParameter("password");
		String vcode = (String)request.getSession().getAttribute("vcode");
		if(vcode==null || !captcha.equals(vcode)) {
			responseMap.put("success", "false");
			responseMap.put("info", "验证码错误！");
			return responseMap;
		}
		try {
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("staff_code", staff_code);
			param.put("password", password);
			List<User> users = userService.login(param);
			if(users.size()>1){
				responseMap.put("success", "false");
				responseMap.put("info", "登陆失败,你输入的员工编码:"+staff_code+"数据库存在"+users.size()+"条记录,请联系管理员");
				return responseMap;
			}
			if(users.size()==1) {
				responseMap.put("success", "true");
				responseMap.put("info", "登录成功！");
				request.getSession().setAttribute("login_localtion",(request.getParameter("login_localtion")));//设置登陆地点,货物入库的时候入库地点为这个值
				request.getSession().setAttribute("user", users.get(0)); 
				request.getSession().setAttribute("loginUserName", users.get(0).getName()); 
				return responseMap;
			}else {
				responseMap.put("success", "false");
				responseMap.put("info", "员工编码或密码错误！");
				return responseMap;
			}
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", "登陆失败!"+e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	
	/**
	 * 获取所有菜单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/menus",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> getMenus(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		User user = (User)request.getSession().getAttribute("user");
		List<Menu> list = menuService.getMenuListByUserId(user.getStaff_id());
		responseMap.put("success", "true");
		responseMap.put("data", list);
		return responseMap;
	}
	
	/**
	 * 获取用户列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/users")
	public @ResponseBody Map<String,Object> getUsers(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		PageInfo pi = new PageInfo(request);
		List<User> userList = userService.getUserList(pi);
		responseMap.put("totalCount", userService.getTotal());
		responseMap.put("rows", userList);
		return responseMap;
	}
	
	/**
	 * 保存用户信息（新增用户or编辑用户）
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> saveOrUpdate(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		DateFormat format= new SimpleDateFormat("yyyy-MM-dd");
		String id = request.getParameter("staff_id");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String identid = request.getParameter("identid");
		String addr = request.getParameter("addr");
		String area = request.getParameter("area");
		String born = request.getParameter("born");
		String tellNbr = request.getParameter("tell_nbr");
		String homeNbr = request.getParameter("home_nbr");
		String weight = request.getParameter("weight");
		String hight = request.getParameter("hight");
		String emerg = request.getParameter("emerg");
		String empDate = request.getParameter("emp_date");
		String roleList = request.getParameter("roleList");
		String postId = request.getParameter("roleList");
		String staff_code = request.getParameter("staff_code");
		
		try {
			//编辑用户信息
//			if(!"".equals(id)) {
//				Map<String,Object> param = new HashMap<String,Object>();
//				param.put("id", id);
//				User user = userService.getUser(param);
//				user.setName(name);
//				//表示修改了密码
//				if(!"".equals(password)) {
//					user.setPassword(password);
//				}
//				param.put("user_id", id);
//				param.put("roleList", roleList);
//				userService.updateUser(user, param);
//				responseMap.put("success", "true");
//				responseMap.put("info", "编辑成功！");
//			}
//			//新增用户信息
//			else {
				Map<String,Object> param = new HashMap<String, Object>();
				param.put("staff_code", staff_code);
				List<User> users = userService.getUser(param);
				if(users.size()>0){
					responseMap.put("success", false);
					responseMap.put("info", "新增用户失败,你输入的员工编码:"+staff_code+"数据库已经存在"+users.size()+"条记录,请检查!");
					return responseMap;
				}
				param.clear();
				User user = new User();
				String newid = Util.getUUID();
				user.setStaff_id(newid);
				user.setStaff_code(Long.parseLong(staff_code));
				user.setEmp_date(format.parse(empDate));
				user.setName(name);
				user.setPassword(password);
				user.setIdentid(identid);
				user.setAddr(addr);
				user.setArea(area);
				user.setBorn(format.parse(born));
				user.setTell_nbr(tellNbr); 
				user.setHome_nbr(homeNbr);
				user.setWeight(Double.parseDouble(weight));
				user.setHight(Double.parseDouble(hight));
				user.setPost_id(Integer.parseInt(postId));
				user.setEmerg(emerg);
				param.put("user_id", newid);
				param.put("menu_role", roleList);
				userService.insertUser(user, param);
				responseMap.put("method", "Create");
				responseMap.put("success", true);
				responseMap.put("info", "新增成功！");
//			}
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	/**
	 * 删除用户
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/remove",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> remove(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		String ids = request.getParameter("ids");
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("ids", ids);
		try {
			userService.deleteUser(param);
			responseMap.put("success", "true");
			responseMap.put("info", "删除成功！");
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
	/**
	 * 修改密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> changePassword(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		User user =(User)request.getSession().getAttribute("user");
		try {
			//验证通过，允许修改密码
			if(oldPassword.equals(user.getPassword())) {
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("id", user.getStaff_id());
				param.put("newPassword", newPassword);
				userService.changeUserPassword(param);
				user.setPassword(newPassword);
				//更新session中的user密码信息
				request.getSession().setAttribute("user", user);
				responseMap.put("success", "true");
				responseMap.put("info", "修改密码成功！");
			}else {
				responseMap.put("success", "false");
				responseMap.put("info", "原密码错误！");
			}
			return responseMap;
		}catch(Exception e) {
			e.printStackTrace();
			responseMap.put("info", e.getClass()+":"+e.getMessage());
			return responseMap;
		}
	}
}
